local desc_joyKJ_mode = [[
  # 欢乐抗金简介
  ___

  规则：玩家身份固定为反，AI身份固定主忠。执行1主3中4反8人场。

  需要自行添加至少4个AI。游戏开始时当真人玩家数为3，主忠AI有随机1层增益buff。为4每3轮主忠AI会再增加一层随机增益buff。

  增益buff：摸牌阶段摸牌多增加标记数；最大体力与体力+1。

  将池：巅峰神塔白名单随机抽选30个武将，并从中随机获取6个武将依次选择。

  卡组：巅峰神塔白名单卡组。

  胜利条件：击败主忠阵营所有AI

  失败条件：玩家阵营全部阵亡。或自由选将不在随机抽选30个武将中

]]

local joykj_test = false  --开启测试可以自由选将
local whilecards = {"standard","standard_cards","maneuvering","lang_cards"} --白名单卡组
local addbuffs = {"@slash_dmg","addmaxhp"} --主忠AI增强buff选项
local buffcdit = {threemans = 3,fourmans ={4,3}}  --threemans为3玩家人数，当大于等于这个值主忠AI会有增强buff。fourmans也如此，但里面3是轮数条件

local joyKJ_getLogic = function()
  local joyKJ_logic = GameLogic:subclass("joyKJ_logic")

  function joyKJ_logic:initialize(room)
    GameLogic.initialize(self, room)
    room.settings.preferredLuckTime = 3
    self.role_table[8] = { "lord", "rebel", "rebel", "rebel", "rebel", "rebel", "rebel", "rebel" }
  end

  function GameLogic:prepareForStart()
    local room = self.room
    local players = room.players

    self:addTriggerSkill(GameRule)
    for _, trig in ipairs(Fk.global_trigger) do
      if trig.name ~= "mobile_effect" then  --关闭手杀特效
        self:addTriggerSkill(trig)
      end
    end
    self.room:sendLog{ type = "$GameStart" }
  end

  function joyKJ_logic:prepareDrawPile()
    local room = self.room
    local allCardIds = Fk:getAllCardIds()
    --重新过滤卡组
    local filterCardIds = {}
    local while_cards = table.clone(whilecards)
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(while_cards,card.package.name) then
          table.removeOne(allCardIds, id)
          table.insert(room.void, id)
          room:setCardArea(id, Card.Void, nil)
        end
      end
      if table.contains(while_cards,card.package.name) then
        if not card.is_derived then
          table.insert(filterCardIds,id)
        end
      end
    end

    table.shuffle(filterCardIds)
    room.draw_pile = filterCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
  end

  function joyKJ_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    roles = table.clone(roles)
    table.shuffle(roles)
    local humans = {}
    local robots = {}
    for _,pr in ipairs(room.players) do
      if pr.id > 0 then 
        table.insert(humans,pr)
      else
        table.insert(robots,pr)
      end
    end
    if #humans > 4 then --默认主反模式
      for i = 1, n do
        local p = room.players[i]
        p.role = roles[i]
        if p.role == "lord" then
          p.role_shown = true
          room:broadcastProperty(p, "role")
        else
          room:notifyProperty(p, p, "role")
        end
      end
      return
    end
    --欢乐抗金
    local handleAIRole = function(num,setrole)
      for i = 1 ,num do
        local human_friai = table.random(robots)
        human_friai.role = setrole
        table.removeOne(robots,human_friai)
      end
    end
    table.forEach(humans,function(pr)
      pr.role = "rebel"
    end)
    local remain_ai = 4 - #humans
    if remain_ai > 0 then
      handleAIRole(remain_ai,"rebel")
      handleAIRole(#robots,"loyalist")
    else
      handleAIRole(#robots,"loyalist")
    end
    local lord = table.find(room.players,function(pr)
      if pr.id < 0 and pr.role == "loyalist" then return true end
    end)
    lord.role = "lord"
    lord.role_shown = true
    room:broadcastProperty(lord, "role")
    for i = 1, n do
      local p = room.players[i]
      if p.role ~= "lord" then
        p.role_shown = true
        room:notifyProperty(p, p, "role")
        room:broadcastProperty(p, "role")
      end
    end
  end

  function joyKJ_logic:chooseGenerals()
    local room = self.room
    -- local generalNum = room.settings.preferredLuckTime
    local generalNum = 6
    local lord = room:getLord()
    room.current = lord
    local nolords = {}
    local whilegens = table.random(GensLimts:getToTalGens(),30)
    table.shuffle(whilegens)
    local human = 0
    for _, p in ipairs(room.players) do
      if p.role ~= "lord" then
        table.insert(nolords,p)
      end
      if p.id > 0 then
        human = human + 1
      else
        -- p.ai = LangAI:new(p)
      end
      -- p.role_shown = true
      -- room:broadcastProperty(p, "role")
    end
    self.all_selgens = table.clone(whilegens)
    self.humans_num = human

    local handleSelGen = function(who,g)
      room:setPlayerGeneral(who, g, true)
      room:askForChooseKingdom({who})
      room:broadcastProperty(who, "general")
      room:broadcastProperty(who, "kingdom")
    end
    handleSelGen(lord,table.remove(whilegens,1))
    for _,pr in ipairs(nolords) do
      if pr.id < 0 then
        handleSelGen(pr,table.remove(whilegens,1))
      else
        local filtgens = table.random(whilegens,generalNum) 
        local selgen = room:askForGeneral(pr, filtgens, 1,true)
        table.removeOne(whilegens,selgen)
        handleSelGen(pr,selgen)
      end
    end
  end
  return joyKJ_logic
end

local handleAddBuff = function(who,room)
  local randbuff = table.random(addbuffs)
  if string.find(randbuff,"@") then
    room:addPlayerMark(who,randbuff,1)
  else
    room:changeMaxHp(who, 1)
    room:recover({
      who = who,
      num = 1,
      recoverBy = who,
      skillName = "#joyKJ_rule"
    })
  end
end
--欢乐抗金模式
local joyKJ_rule = fk.CreateTriggerSkill{
  name = "#joyKJ_rule",
  priority = 0.001,
  refresh_events = {fk.GameStart,fk.RoundStart,fk.Deathed,fk.GameOverJudge},
  can_refresh = function(self, event, target, player, data)
    if event == fk.GameStart then
      return player == target and player.role == "lord"
    elseif event == fk.RoundStart then
      if player == target and player.role == "lord" then
        local humans = player.room.logic.humans_num
        local round = player.room:getTag("RoundCount")
        return humans == buffcdit.fourmans[1] and round % buffcdit.fourmans[2] == 0 --4人ai增强
      end
    elseif event == fk.Deathed then
      return player == target
    elseif event == fk.GameOverJudge then
      return player == target
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      local all_selgens = room.logic.all_selgens
      local humans = table.filter(room.players,function(pr)
        if pr.id > 0 then return true end
      end)
      humans = table.map(humans,function(pr)
        return pr.general
      end)
      if not joykj_test and (not GensLimts:gensIsInConf(humans,all_selgens) or not all_selgens) then 
        room:doBroadcastNotify("ShowToast", "选将不在原选将框内或不符合游戏规则，游戏结束")
        room:gameOver("lord")
        return
      end
      room:setTag("SkipGameRule", true)
      local lordcamps_ai = table.filter(room.players,function(pr)
        if pr.id < 0 and (pr.role == "lord" or pr.role == "loyalist") then return true end
      end)
      if #humans >= buffcdit.threemans then --3人ai增加1层buff
        for _ ,pr in ipairs(lordcamps_ai) do
          room:handleAddLoseSkills(pr, "wjsl_zhenfen", nil, false)
          handleAddBuff(pr,room)
        end
      end
    elseif event == fk.RoundStart then
      for _,pr in ipairs(room.alive_players) do
        if pr.id < 0 and (pr.role == "lord" or pr.role == "loyalist") then
          handleAddBuff(pr,room)
        end
      end
    elseif event == fk.Deathed then
      -- room:setTag("SkipNormalDeathProcess", true)
      if player.role == "lord" or player.role == "loyalist" then
        local from = data.damage and data.damage.from
        if from then
          room:drawCards(from, 3,self.name)
        end
      end
    elseif event == fk.GameOverJudge then
      room:setTag("SkipGameRule", true)
      local alives = room.alive_players
      local who = room:getPlayerById(data.who)
      if not who then if #alives == 1 then room:gameOver(alives[1].role) end return end
      local campscfg = {rebel=1,lord=2,loyalist=2}
      local winrole
      for i=1,#alives do
        local chkplayer = alives[i]
        if not winrole then
          winrole = campscfg[chkplayer.role]
        else
          if not chkplayer.dead and campscfg[chkplayer.role] ~= winrole then
            winrole = nil
            break
          end
        end
      end
      if winrole then room:gameOver(alives[1].role) end
      return
    end
  end,
}
Fk:addSkill(joyKJ_rule)
local joyKJ_mode = fk.CreateGameMode{
  name = "joyKJ_mode",
  minPlayer = 8,
  maxPlayer = 8,
  rule = joyKJ_rule,
  logic = joyKJ_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 10s", passed = playedTime >= 10 } }
    if Self.role ~= "lord" then
      table.insert(surrenderJudge, { text = "only you alive", passed = #Fk:currentRoom().alive_players <= 2 })
    end
    return surrenderJudge
  end,
}

Fk:loadTranslationTable{
  ["joyKJ_mode"] = "欢乐抗金",
  ["joyKJ_rule"] = "欢乐抗金",

  ["time limitation: 10s"] = "游戏时长达到10秒",
  ["only you alive"] = "仅剩两人存活",

  [":joyKJ_mode"] = desc_joyKJ_mode,
}

return joyKJ_mode
